﻿import {Pipe, PipeTransform} from 'angular2/core';

@Pipe({ name: 'groupBy', pure: false })
export class GroupBy implements PipeTransform {
    
    transform(input: any, [config = '+']): any {

        if (!Array.isArray(input)) return input;

        if (!Array.isArray(config) || (Array.isArray(config) && config.length == 1)) {
            var key: string = !Array.isArray(config) ? config : config[0];
            var desc = key.substr(0, 1) == '-';

            var data = input;

            if (!(data && key)) return;

            var result = [];
            for (var i = 0; i < data.length; i++) {
                if (!result[data[i][key]])
                    result[data[i][key]] = [];
                result[data[i][key]].push(data[i])
            }

            return Array.from(result);
        }
    }
}